//
//  HNAPayMainViewController.m
//  HNAPayMobileSDK
//
//  Created by Ly_work on 15/11/18.
//  Copyright © 2015年 usolv. All rights reserved.
//

#import "HNAPayMainViewController.h"
#import "HNAPayWebView.h"
#import "HNAPayURLRequest.h"
#import "HNAPayDefaultDefine.h"

#import "FRMS.h"

#define HNACLOSEDURL @"/pay/front/callback.shtml"

@interface HNAPayMainViewController ()

@property(strong ,nonatomic) HNAPayWebView *webViewHnaPay;

@end

@implementation HNAPayMainViewController
#pragma mark ---iOS7以后方法，动态设置状态栏
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}
- (void)viewDidLoad{
    [super viewDidLoad];
    
    /*
    ******不使用SDK获取设备指纹，完全采用js获取******
     
    //邦盛技术人员建议参数，失败尝试次数5，失败关闭接口时间60s
    [[FRMS sharedInstance] loadUrl:@"https://rmsfnprtnewtest.hnapay.com/public/generate/post"
                      andFailCount:5
                    andWaitSeconds:60
                         andCustID:@"1234"];
    //重置接口，用于接口关闭后重新打开接口，测试使用
//    [[FRMS sharedInstance] shutdown];
//    [[FRMS sharedInstance] reset];
    
    //YES表示无视本地缓存, 强制重新获取新的设备指纹外码; NO表示优先获取本地缓存的设备指纹
    NSDictionary *resultDic = [[FRMS sharedInstance] getFingerprint:NO];
    if (resultDic != nil) {
        NSString *dfp = [resultDic valueForKey:@"dfp"];
        NSString *error = [resultDic valueForKey:@"Error"];
        if (dfp != nil) {
            NSLog(@"Fingerprint******success -> %@",dfp); // 取到设备指纹返回值
            [[NSUserDefaults standardUserDefaults] setObject:dfp forKey:@"fingerPrint"];
        }else{
            NSLog(@"Fingerprint******error -> %@",error); //获取失败，返回error
        }
        
    }else{
        NSLog(@"Fingerprint******error -> 无法获取设备指纹"); //获取失败，返回nil
    }
    
     */
     
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    HNAPayURLRequest *request = [HNAPayURLRequest creatRequestWithURL:HNAPAYWEBURL method:@"POST" parameter:self.mDparameters encoding:NSUTF8StringEncoding];
    CGRect webViewRect = (CGRect){0 ,0 ,SCREEN_WIDTH ,SCREEN_HEIGHT};
//    if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10,0,0}]) {
//        NSLog(@"Hello from > iOS 10.0.0");
//        webViewRect = (CGRect){0 ,0 ,SCREEN_WIDTH ,SCREEN_HEIGHT};
//    }
    __strong HNAPayMainViewController *strongSelf = self;
    self.webViewHnaPay = [HNAPayWebView  hnaPayWebViewWithFrame:webViewRect loadRequest:request
                                                         loaded:^(UIWebView *aWebView) {
//                                                             NSLog(@"Loaded %@", aWebView.request.URL);
                                                         }
                                                         failed:^(UIWebView *aWebView, NSError *error) {
//                                                             NSLog(@"Failed loading with error: %@", error.localizedDescription);
                                                         }
                                                    loadStarted:^(UIWebView *aWebView) {
                                                        NSLog(@"Started loading");
                                                    }
                                                     shouldLoad:^BOOL(UIWebView *aWebView, NSURLRequest *request, UIWebViewNavigationType navigationType) {
                                                         NSString *relativePathString = request.URL.absoluteString;
                                                         NSString *relativePath = request.mainDocumentURL.relativePath;
                                                         
//                                                         NSLog(@"=====relativePathString%@",relativePathString);
//                                                         NSLog(@"-----relativePath%@",relativePath);
                                                         NSRange rangeEmail = [relativePathString rangeOfString:@"http://mobi/outmail?url="];
                                                         if ( [request.mainDocumentURL.relativePath isEqualToString:HNACLOSEDURL]) {
                                                             //关闭按钮点击。。。
//                                                             NSLog(@"点击关闭按钮！！！！");
                                                             [strongSelf closeHNAPaySDK];
                                                             return NO;
                                                         }else if (rangeEmail.location != NSNotFound){
//                                                             NSLog(@"打开系统浏览器！！！！");
                                                             
                                                             return NO;
                                                         }
                                                         return YES;
                                                     }];
    [self.webViewHnaPay isShowProgressView:YES];
//    [self.webViewHnaPay removeAllCache];
    [self.view addSubview: self.webViewHnaPay];
    
}


//- (void)generateOnSuccess :(NSString *) fingerPrint andTraceId :(NSString *)traceId
//{
//    NSLog(@"success -> %@",fingerPrint); // 取到设备指纹返回值
//    NSLog(@"TraceId -> %@",traceId);//获取TraceID
////    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:fingerPrint message:traceId delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
////    [alert show];
//
//    
//    [[NSUserDefaults standardUserDefaults] setObject:fingerPrint forKey:@"fingerPrint"];
//}
//
//- (void)generateOnFailed :(NSError *) error
//{
//    NSLog(@"error -> %@",[error description]); //获取异常信息
//}



-(void)closeHNAPaySDK{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:NOTIFICATION_NAME_CLOSED object:nil userInfo:nil];
    //    [self.webViewHnaPay removeAllCache];
    //    [[BSFingerSDK sharedInstance] cancelAll];//停止后台服务并释放资源
    //    [[self topViewController] dismissViewControllerAnimated:YES completion:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (UIViewController*)topViewController
{
    return [self topViewControllerWithRootViewController:[[[[UIApplication sharedApplication] delegate] window] rootViewController]];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}
-(void)dealloc{
    [self.webViewHnaPay stopLoading];
//    [self.webViewHnaPay removeAllCache];
    self.webViewHnaPay = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
